package edu.cuc.spring.xml.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public abstract class  TimeServerSpring {
    public TimeServerSpring() {
    }
    private NioEventLoopGroup workGroup;
    private NioEventLoopGroup bossGroup;
    private ServerBootstrap bootStrap;
    private int port;


    public void setPort(int port) {
        this.port = port;
    }

    public void setWorkGroup(NioEventLoopGroup workGroup) {
        this.workGroup = workGroup;
    }

    public void setBossGroup(NioEventLoopGroup bossGroup) {
        this.bossGroup = bossGroup;
    }

    public void setBootStrap(ServerBootstrap bootStrap) {
        this.bootStrap = bootStrap;
    }

    public void bind() {
        System.out.println("sss");
        bootStrap.group(workGroup, bossGroup).channel(NioServerSocketChannel.class).childOption(ChannelOption.SO_BACKLOG, 1024)
                .childHandler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(getHandler());
                    }
                });
        ChannelFuture f = bootStrap.bind(port);
        f.channel().closeFuture();
    }

    public void close() {
        workGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
    }

    protected abstract TimeServerHandler getHandler();
}
